import { useState, useEffect, useCallback, useRef } from 'react'
import { 
  uploadWithResume, 
  pauseUpload, 
  resumeUpload, 
  cancelUpload,
  getUploadTask,
  getAllUploadTasks,
  clearCompletedTasks,
  clearAllTasks,
  hasUnfinishedTasks,
  getUnfinishedTasks,
  retryFailedUpload,
  type ResumeUploadResult,
  type ResumeUploadProgressCallback
} from '../utils/resumeOssUpload'
import { UploadTask } from '../utils/resumeUpload'

// Hook配置接口
export interface UseResumeUploadConfig {
  // 是否自动清理已完成的任务
  autoClearCompleted?: boolean
  // 是否在组件挂载时检查未完成的任务
  checkUnfinishedOnMount?: boolean
  // 清理间隔（毫秒）
  clearInterval?: number
}

// Hook返回值接口
export interface UseResumeUploadReturn {
  // 上传状态
  isUploading: boolean
  uploadProgress: number
  uploadSpeed: number
  remainingTime: number
  currentTask: UploadTask | null
  
  // 任务列表
  allTasks: UploadTask[]
  unfinishedTasks: UploadTask[]
  
  // 上传方法
  uploadFile: (file: File, onProgress?: ResumeUploadProgressCallback) => Promise<ResumeUploadResult>
  uploadMultipleFiles: (files: File[], onProgress?: (fileIndex: number, task: UploadTask) => void) => Promise<ResumeUploadResult[]>
  
  // 任务控制方法
  pauseCurrentUpload: () => Promise<boolean>
  resumeCurrentUpload: (file: File) => Promise<ResumeUploadResult>
  cancelCurrentUpload: () => Promise<boolean>
  retryFailedUpload: (taskId: string, file: File) => Promise<ResumeUploadResult>
  
  // 任务管理方法
  getTask: (taskId: string) => UploadTask | undefined
  clearCompleted: () => void
  clearAll: () => void
  
  // 状态检查
  hasUnfinished: boolean
  refreshTasks: () => void
}

// 默认配置
const DEFAULT_CONFIG: UseResumeUploadConfig = {
  autoClearCompleted: true,
  checkUnfinishedOnMount: true,
  clearInterval: 30000 // 30秒
}

export const useResumeUpload = (config: UseResumeUploadConfig = {}): UseResumeUploadReturn => {
  const finalConfig = { ...DEFAULT_CONFIG, ...config }
  
  // 状态管理
  const [isUploading, setIsUploading] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [uploadSpeed, setUploadSpeed] = useState(0)
  const [remainingTime, setRemainingTime] = useState(0)
  const [currentTask, setCurrentTask] = useState<UploadTask | null>(null)
  const [allTasks, setAllTasks] = useState<UploadTask[]>([])
  const [unfinishedTasks, setUnfinishedTasks] = useState<UploadTask[]>([])
  const [hasUnfinished, setHasUnfinished] = useState(false)
  
  // 引用
  const currentFileRef = useRef<File | null>(null)
  const clearIntervalRef = useRef<NodeJS.Timeout | null>(null)
  
  // 刷新任务列表
  const refreshTasks = useCallback(() => {
    const tasks = getAllUploadTasks()
    const unfinished = getUnfinishedTasks()
    
    setAllTasks(tasks)
    setUnfinishedTasks(unfinished)
    setHasUnfinished(unfinished.length > 0)
  }, [])
  
  // 计算上传速度和剩余时间
  const calculateSpeedAndTime = useCallback((task: UploadTask) => {
    if (task.status !== 'uploading' || task.startTime === 0) {
      return { speed: 0, remainingTime: 0 }
    }
    
    const elapsed = (Date.now() - task.startTime) / 1000 // 秒
    const uploadedBytes = (task.completedParts / task.totalParts) * task.fileSize
    const speed = uploadedBytes / elapsed // bytes/s
    const remainingBytes = task.fileSize - uploadedBytes
    const remainingTime = remainingBytes / speed // 秒
    
    return {
      speed: isFinite(speed) ? speed : 0,
      remainingTime: isFinite(remainingTime) ? remainingTime : 0
    }
  }, [])
  
  // 处理上传进度
  const handleProgress = useCallback((task: UploadTask) => {
    setCurrentTask(task)
    setUploadProgress(task.progress)
    
    if (task.status === 'uploading') {
      setIsUploading(true)
      const { speed, remainingTime } = calculateSpeedAndTime(task)
      setUploadSpeed(speed)
      setRemainingTime(remainingTime)
    } else if (task.status === 'completed') {
      setIsUploading(false)
      setUploadSpeed(0)
      setRemainingTime(0)
      setCurrentTask(null)
    } else if (task.status === 'failed' || task.status === 'paused') {
      setIsUploading(false)
    }
    
    // 刷新任务列表
    refreshTasks()
  }, [calculateSpeedAndTime, refreshTasks])
  
  // 上传单个文件
  const uploadFile = useCallback(async (
    file: File, 
    onProgress?: ResumeUploadProgressCallback
  ): Promise<ResumeUploadResult> => {
    currentFileRef.current = file
    
    const progressCallback: ResumeUploadProgressCallback = (task) => {
      handleProgress(task)
      if (onProgress) {
        onProgress(task)
      }
    }
    
    const result = await uploadWithResume(file, progressCallback)
    
    // 如果上传完成或失败，清理当前文件引用
    if (result.success || result.error) {
      currentFileRef.current = null
    }
    
    return result
  }, [handleProgress])
  
  // 批量上传文件
  const uploadMultipleFiles = useCallback(async (
    files: File[],
    onProgress?: (fileIndex: number, task: UploadTask) => void
  ): Promise<ResumeUploadResult[]> => {
    const results: ResumeUploadResult[] = []
    
    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      const result = await uploadFile(file, (task) => {
        if (onProgress) {
          onProgress(i, task)
        }
      })
      results.push(result)
    }
    
    return results
  }, [uploadFile])
  
  // 暂停当前上传
  const pauseCurrentUpload = useCallback(async (): Promise<boolean> => {
    if (!currentTask) {
      return false
    }
    
    const success = await pauseUpload(currentTask.id)
    if (success) {
      setIsUploading(false)
      setCurrentTask(prev => prev ? { ...prev, status: 'paused' } : null)
      refreshTasks()
    }
    
    return success
  }, [currentTask, refreshTasks])
  
  // 恢复当前上传
  const resumeCurrentUpload = useCallback(async (file: File): Promise<ResumeUploadResult> => {
    if (!currentTask) {
      return {
        success: false,
        error: '没有可恢复的上传任务'
      }
    }
    
    currentFileRef.current = file
    
    const progressCallback: ResumeUploadProgressCallback = (task) => {
      handleProgress(task)
    }
    
    const result = await resumeUpload(currentTask.id, file, progressCallback)
    
    if (result.success || result.error) {
      currentFileRef.current = null
    }
    
    return result
  }, [currentTask, handleProgress])
  
  // 取消当前上传
  const cancelCurrentUpload = useCallback(async (): Promise<boolean> => {
    if (!currentTask) {
      return false
    }
    
    const success = await cancelUpload(currentTask.id)
    if (success) {
      setIsUploading(false)
      setUploadProgress(0)
      setUploadSpeed(0)
      setRemainingTime(0)
      setCurrentTask(null)
      currentFileRef.current = null
      refreshTasks()
    }
    
    return success
  }, [currentTask, refreshTasks])
  
  // 重试失败的上传
  const retryFailedUploadTask = useCallback(async (
    taskId: string, 
    file: File
  ): Promise<ResumeUploadResult> => {
    const progressCallback: ResumeUploadProgressCallback = (task) => {
      handleProgress(task)
    }
    
    return await retryFailedUpload(taskId, file, progressCallback)
  }, [handleProgress])
  
  // 获取任务信息
  const getTask = useCallback((taskId: string): UploadTask | undefined => {
    return getUploadTask(taskId)
  }, [])
  
  // 清理已完成的任务
  const clearCompleted = useCallback(() => {
    clearCompletedTasks()
    refreshTasks()
  }, [refreshTasks])
  
  // 清理所有任务
  const clearAll = useCallback(() => {
    clearAllTasks()
    setIsUploading(false)
    setUploadProgress(0)
    setUploadSpeed(0)
    setRemainingTime(0)
    setCurrentTask(null)
    setAllTasks([])
    setUnfinishedTasks([])
    setHasUnfinished(false)
    currentFileRef.current = null
  }, [])
  
  // 组件挂载时的初始化
  useEffect(() => {
    if (finalConfig.checkUnfinishedOnMount) {
      refreshTasks()
    }
    
    // 设置自动清理定时器
    if (finalConfig.autoClearCompleted && finalConfig.clearInterval) {
      clearIntervalRef.current = setInterval(() => {
        clearCompleted()
      }, finalConfig.clearInterval)
    }
    
    return () => {
      if (clearIntervalRef.current) {
        clearInterval(clearIntervalRef.current)
      }
    }
  }, [finalConfig, refreshTasks, clearCompleted])
  
  // 组件卸载时清理
  useEffect(() => {
    return () => {
      if (clearIntervalRef.current) {
        clearInterval(clearIntervalRef.current)
      }
    }
  }, [])
  
  return {
    // 状态
    isUploading,
    uploadProgress,
    uploadSpeed,
    remainingTime,
    currentTask,
    
    // 任务列表
    allTasks,
    unfinishedTasks,
    
    // 上传方法
    uploadFile,
    uploadMultipleFiles,
    
    // 任务控制方法
    pauseCurrentUpload,
    resumeCurrentUpload,
    cancelCurrentUpload,
    retryFailedUpload: retryFailedUploadTask,
    
    // 任务管理方法
    getTask,
    clearCompleted,
    clearAll,
    
    // 状态检查
    hasUnfinished,
    refreshTasks
  }
}
